package com.sky.service;

import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
public class UploadService {
    /**
     * 文件上传 底层原理 会自动和request.getInputStream()融合一起，请求流
     * @param dir 分类文件夹
     * @return
     */
    public Result<String> uploadImg(MultipartFile multipartFile, String dir){

        try {
            log.info("文件信息,{}",multipartFile);
            // 1,获取文件名和后缀
            String realFileName = multipartFile.getOriginalFilename();
            String imgSuffix = realFileName.substring(realFileName.lastIndexOf("."));

            //2,生成的唯一文件名
            String newFileName = UUID.randomUUID().toString() + imgSuffix;

            //3,日期目录
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = dateFormat.format(new Date());

            //4,指定文件上传的目录
            File targetPath = new File("F://tmp/"+dir,datePath);
                        if(!targetPath.exists()){
                            targetPath.mkdirs();//递归创建
            }
            //5,指定文件上传以后的服务器的完整文件名
            File targetFileName = new File(targetPath,newFileName);

            //6,文件上传到指定目录
            multipartFile.transferTo(targetFileName);

            //7、返回可访问的网址
            String fileName = dir + "/" + datePath + "/" + newFileName;
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            String localAddr = request.getLocalAddr();
            int serverPort = request.getServerPort();
            log.info("上传成功！");
            return Result.success("http://"+ localAddr+":"+serverPort+"/uploadimg/"+fileName);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("上传失败！");
            return Result.error("上传失败！");
        }
    }
}
